<template>
	<view>
		<view class="welfare-content" style="background-color: #FFF;" v-if="!showAddress">
			<view style="height: 500rpx;width: 100%;margin: 0 auto;" class="swiper-content">
				<swiper class="screen-swiper" :class="dotStyle?'square-dot':'round-dot'" 
					:circular="true" :autoplay="true" interval="5000" duration="500">
					<swiper-item v-for="(item,index) in swiperList" :key="index">
						<image :src="item.broadcastImage" mode="aspectFill" style="height: 100%;">
						</image>
					</swiper-item>
				</swiper>
			</view>
			<!-- 推广链接 -->
			<!-- <view class="spread">
				<view class="spread-wrapper">
					<view class="item" :class="'num'+index" v-for="(item, index) in spreadList" :key="index" @click="jump(item)">
						<view class="title">{{item.linkerName}}</view>
						<view class="desc">{{item.linkerDesc || ''}}</view>
					</view>
				</view>
			</view> -->
			<view class="xcx" v-if="popularize.broadcastImage" @click="jumpXcx">
				<image :src="popularize.broadcastImage" mode="aspectFill" style="height: 100%;">
				</image>
			</view>
			<view class="productList" style="background: #fff;">
				<view style="height: 80rpx;line-height: 80rpx;font-size: 40rpx;font-weight: bold;margin-top: 20rpx;">福利兑换</view>
				<view class='list row-between-wrapper on'>
				  <block v-for="(item, index) in productList" :key="index">
					 <view class='item on'>
						<view class='pictrue on'>
						   <image :src="item.thumb" class="on"></image>
						</view>
						<view class='text on'>
						   <view class='name line1'>{{item.goodsName}}</view>
						   <view class='vip on'>
							  当前已有{{item.saleCount}}人领取
						   </view>
						   <view class='money acea-row font-color on'>
							   <view class="left acea-row">
									<image src="../../static/jf.jpg" mode="" style="width: 40rpx;height: 40rpx;"></image>
									<text class='num'>{{item.credit}}</text>
							   </view>
							   <button class="receive" @click="receive(item)" v-if="item.stock > 0">点击领取</button>
							   <!-- <button class="not" @click="() => {
								   showQrcodeModal = true
								   hideTabBar()
							   }" v-else>暂无库存</button> -->
							   <button class="not" v-else>暂无库存</button>
							</view>
						</view>
					 </view>
				  </block>
				  <!-- <navigator class='item {{is_switch==true?"":"on"}}' hover-class='none' wx:for='{{productList}}' url='/pages/goods_details/index?id={{item.id}}' wx:key='index'>
					 
				  </navigator> -->
				  <view class='loadingicon acea-row row-center-wrapper' v-if='productList.length > 0 && !loadend'>
					 <text class='loading iconfont icon-jiazai' :hidden='loading==false'></text>{{loadTitle}}
				  </view>
			   </view>
			</view>
			
			<!-- 企业二维码弹框 -->
			<view class="cu-modal" :class="showQrcodeModal?'show':''" @click="() => {
						showQrcodeModal = false
						showTabBar()
					}">
				<view class="cu-dialog">
					<view>
						<image src="../../static/rankbg.png"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 显示收货地址 -->
		<Address @back="{
			showAddress = false
			showReceiveModal = true
		}" @selectAdr="record => {
			showAddress = false
			showReceiveModal = true
			addressInfo = record
		}" v-else />
		
		<!-- 确认领取弹框 -->
		<view class="cu-modal receive-modal" :class="showReceiveModal?'show':''" @click.stop="() => {
			showReceiveModal = false
			showTabBar()
		}">
			<view class="cu-dialog" @click.stop="showReceiveModal=true">
				<view class="dialog-content">
					<view class="address" v-if="buyInfo.goodsCategoryId == 2">
						<view class="title">确认收货地址</view>
						<view class="desc acea-row" @click.stop="openAddress">
							<view class="detail">
								<template v-if="addressInfo.addressId != ''">
									<view>{{ addressInfo.consignee }}&nbsp;&nbsp;{{addressInfo.phone}}</view>
									<view style="margin-top: 30rpx;">{{addressInfo.address}}</view>
								</template>
								<template v-else>请选择收货地址</template>
							</view>
							<view class="more">
								<image src="../../static/arrow-right-bold.png" mode="" style="width: 40rpx;height: 40rpx;"></image>
							</view>
						</view>
					</view>
					<view class="address user-extra-info" v-if="buyInfo.goodsCategoryId == 1 || (buyInfo.goodsCategoryId == 2 && extraFieldList.length > 0)">
						<view class="title">用户信息</view>
						<view class="form">
							<template v-if="buyInfo.goodsCategoryId != 2">
								<view class='item acea-row row-between-wrapper'>
									<view class='name'>姓名</view>
									<input type='text' placeholder='请输入姓名' name='consignee' :value="userExtraInfo.consignee" placeholder-class='placeholder'></input>
								</view>
								<view class='item acea-row row-between-wrapper'>
									<view class='name'>手机号码</view>
									<input type='text' placeholder='请输入手机号码' name='phone' :value="userExtraInfo.phone" placeholder-class='placeholder'></input>
								</view>
							</template>
							<view class='item acea-row row-between-wrapper' v-for="(item, index) in extraFieldList" :key="index">
								<view class='name'>{{item.modelName}}</view>
								<input type='text' :placeholder="`请输入${item.modelName}`" :name="item.modelKey" v-model="item.value" placeholder-class='placeholder'></input>
							</view>
						</view>
					</view>
					<view class="goods-detail">
						<view class="acea-row">
							<view class="image">
								<image :src="buyInfo.thumb" mode=""></image>
							</view>
							<view class="info">
								<text>{{ buyInfo.goodsName }}</text>
								<view class="money acea-row">
									<view class="left acea-row">
										<image src="../../static/jf.jpg" mode="" style="width: 40rpx;height: 40rpx;"></image>
										<text class='num'>{{buyInfo.credit}}</text>
									</view>
									<text>x 1</text>
								</view>
							</view>
						</view>
						<button class="buy" @click.stop="buy(buyInfo)">确认领取</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getWelfareList,
		getLinkersList,
		saveLinkerClick
	} from '@/api/welfare.js'
	import { createOrder, createPreviewOrder } from '@/api/order.js'
	import { getUserProfile } from '@/utils/getUserProfile.js'
	import { getUserInfo } from '@/api/user.js'
	import Address from '../../components/address/address.vue'
	export default {
		components: {
			Address
		},
		data() {
			return {
				productList: [], // 产品列表
				loading: false,				
				loadTitle:'加载更多',
				loadend: false, // 加载到底部
				page: 1, // 页数
				pagesize: 10, // 每页条数
				dotStyle: true,
				swiperList: [], // 轮播图
				showReceiveModal: false, // 确认领取弹框
				showQrcodeModal: false, // 弹框
				buyInfo: {}, // 领取商品信息
				addressInfo: {}, // 收货地址
				showAddress: false, // 显示地址
				spreadList: [], // 推广链接
				popularize: {},
				userInfo: {}, // 用户信息
				userExtraInfo: {}, // 用户额外信息
				extraFieldList: [] // 用户额外信息字段
			}
		},
		onTabItemTap(item) {
			this.showReceiveModal = false; // 确认领取弹框
			this.showQrcodeModal = false; // 弹框
			this.buyInfo = {}; // 领取商品信息
			this.addressInfo = {}
			this.userInfo = {}
			this.extraFieldList = []
			this.getList(true)
		},
		onLoad() {
			
		},
		onReady() {
			
		},
		mounted() {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			// 获取推广链接
			this.getLinkersList()
			// 获取商品列表
			this.getList();
			// this.getSchoolList(this.tabProvince);
		},
		methods: {
			jumpXcx() {
				uni.navigateToMiniProgram({
				  appId: 'wxb5d58025839dc97c',
				  success(res) {
				    // 打开成功
					console.log(222);
				  }
				})
			},
			// 获取轮播图
			async getLinkersList() {	
				uni.showLoading({
					title: '数据加载中...',
					mask: true
				});	
				getLinkersList().then(res => {
					uni.hideLoading();
					if (res.code == 200) {
						this.swiperList = res.data.broadcast
						this.spreadList = res.data.linkers
						this.popularize = res.data.popularize // 跳转小程序的图片
					}
				});
			},
			// 获取商品列表
			async getList(isPage) {
				if (isPage) {
					this.loadend = false
					this.page = 1
					this.productList = []
				}
				if (this.loading) return
				if (this.loadend) return
				this.loading = true
				this.loadTitle = ''
				uni.showLoading({
					title: '数据加载中...',
					mask: true
				});
				const query = {
					page: this.page,
					pagesize: this.pagesize
				}
				getWelfareList(query).then(res => {
					uni.hideLoading();
					console.log(res);
					if (res.code == 200) {
						const list = res.data.lists
						this.loadend = list.length < this.pagesize
						this.productList = [ ...this.productList, ...list]
						this.loadTitle = this.loadend ? '我也是有底线的' : '加载更多'
						this.page++
					} else {
						uni.showToast({
							title: '获取数据失败！',
							duration: 1000,
							icon: 'none',
						});
					}
					this.loading = false
				});
				uni.hideLoading()
			},
			// 点击推广链接获取积分并跳转
			async jump(record) {
				saveLinkerClick({id: record.linkerId}).then(res => {
					if (record.linkerUrl) {
						uni.navigateTo({
							url: '../../subpages/outlink?url=' + encodeURIComponent(record.linkerUrl)
						})
					}
				})
			},
			// 领取
			receive(record) {
				let token = uni.getStorageSync("token");
				if (!token) {
					this.getUserProfile(record.goodsId);
				} else {
					this.getUserInfo()
					this.createPreviewOrder(record.goodsId)
				}
			},
			/**获取用户信息*/
			async getUserInfo() {
				let token = uni.getStorageSync("token");
				const {
					data
				} = await getUserInfo(token);
				console.log('u', data);
				this.userInfo = data;
				this.userExtraInfo.phone = data.phone
				this.userExtraInfo.consignee = data.realName
			},
			/**授权登录*/
			async getUserProfile(goodsId) {
				let data = await getUserProfile();
				if (data.code != 200) {
					uni.showToast({
						title: '登录失败！',
						duration: 1000,
						icon: 'none',
					});
				} else {
					this.getUserInfo()
					this.createPreviewOrder(goodsId)
				}
			},
			// 创建订单预览
			createPreviewOrder(goodsId){
				this.buyInfo = {}
				this.addressInfo = {}
				createPreviewOrder({goodsId}).then(res => {
					if (res.code == 200) {
						this.showReceiveModal = true
						this.hideTabBar()
						this.buyInfo = res.data.goods
						res.data.goods.models.forEach(item => {
							item.value = ''
						})
						this.extraFieldList = res.data.goods.models
						this.addressInfo = res.data.consign
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none',
						});
					}
				})
			},
			// 显示tabBar
			showTabBar() {
				wx.showTabBar()
			},
			// 隐藏tabBar
			hideTabBar() {
				wx.hideTabBar()
			},
			// 选择地址
			openAddress() {
				this.showAddress = true
				this.showReceiveModal = false
			},
			// 返回
			back() {
				this.showAddress = false
			},
			// 确认领取
			async buy(info) {
				// 用户信息额外字段
				var extraFieldList = {}
				this.extraFieldList.forEach(item => {
					extraFieldList[item.modelKey] = item.value
				})
				
				
				const query = {
					addressId: this.addressInfo.addressId,
					goodsId: info.goodsId,
					consign: info.goodsCategoryId == 2 ? {...extraFieldList} : {...this.userExtraInfo, ...extraFieldList}
				}
				
				uni.showLoading({
					title: '提交中...',
					mask: true
				});
				createOrder(query).then(res=> {
					uni.hideLoading();
					if (res.code == 200) {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none',
						});
						this.showReceiveModal = false
						this.showTabBar()
					} else {						
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none',
						});
					}
				})
			}
		},
		/**
		   * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function () {
			this.getList();
		}
	}
</script>

<style lang="less" scoped>
@import './index.less';
.user-extra-info{
	padding: 0 !important;
}
.user-extra-info .form{margin: 30rpx 0;text-align: left;}
.user-extra-info .form .item{padding:0 30rpx;height:90rpx;border-top:1rpx solid #eee;}
.user-extra-info .form .item .name{width:195rpx;font-size:30rpx;color:#333;}
.user-extra-info .form .item input{width:475rpx;font-size:30rpx;}
.user-extra-info .form .item .placeholder{color:#ccc;}
.user-extra-info .form .item picker{width:475rpx;}
.user-extra-info .form .item picker .picker{width:410rpx;font-size:30rpx;}
.user-extra-info .form .item picker .iconfont{font-size:43rpx;}
</style>
